package com.suixin.learn.persistence.factory;

import com.suixin.learn.persistence.pojo.Configuration;
import com.suixin.learn.persistence.pojo.MappedStatement;
import com.suixin.learn.persistence.utils.GenericTokenParser;
import com.suixin.learn.persistence.utils.ParameterMapping;
import com.suixin.learn.persistence.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement ps = execute(configuration, statement, params);

        List<E> result = (List<E>) getQueryResult(getClassType(statement.getResultType()),ps.getResultSet());

        return result;
    }

    private PreparedStatement execute(Configuration configuration, MappedStatement statement, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, statement, params);
        preparedStatement.execute();
        return preparedStatement;
    }

    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement statement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        //获取连接
        Connection connection = configuration.getDataSource().getConnection();
        String sql = statement.getSql();

        //sql转换，占位符使用？
        BoundSql boundSql = getBoundSql(sql);

        //获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        //设置参数
        String parameterType = statement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for(int i = 0; i< parameterMappingList.size(); i++){
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String fieldName = parameterMapping.getContent();

            Field declaredField = parameterClass.getDeclaredField(fieldName);
            declaredField.setAccessible(true);

            Object o = declaredField.get(params[0]);

            preparedStatement.setObject(i+1,o);

        }
        return preparedStatement;
    }

    @Override
    public int update(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement ps = execute(configuration, statement, params);
        return ps.getUpdateCount();
    }

    private List<Object> getQueryResult(Class<?> classType, ResultSet resultSet) throws Exception {
        List<Object> resultList = new ArrayList<>();
        while(resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Constructor<?> constructor = classType.getConstructor();
            Object o = constructor.newInstance();
            for(int i=1;i<=metaData.getColumnCount();i++){
                String columnName = metaData.getColumnName(i);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, classType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, resultSet.getObject(columnName));
            }
            resultList.add(o);
        }
        return resultList;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if(null != parameterType){
            return Class.forName(parameterType);
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        return new BoundSql(parse,parameterMappingTokenHandler.getParameterMappings());
    }

}
